<template>
  <div class="p-2">
    <div class="search" v-show="showSearch">
      <el-form
        :model="queryParams"
        ref="queryFormRef"
        :inline="true"
        label-width="68px"
      >
        <el-form-item label="区域名称" prop="name">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入区域名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>

        <el-form-item label="类型" prop="type">
          <el-select v-model="queryParams.type" clearable placeholder="请选择">
            <el-option
              v-for="item in selectArr.typeArr"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">
            搜索
          </el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <el-table
        v-loading="loading"
        :data="organizationList"
        row-key="id"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        ref="treeTableRef"
      >
        <el-table-column label="机构名称" align="left" prop="name" />

        <!--        <el-table-column label="状态" prop="status" width="80">-->
        <!--          <template #default="{ row }">-->
        <!--            <el-tag :type="CommonStatusStyleTypeMap.get(row.status)"-->
        <!--            >{{ row.statusMsg }}-->
        <!--            </el-tag>-->
        <!--          </template>-->
        <!--        </el-table-column>-->

        <el-table-column label="类型" align="center" prop="typeMsg" />

        <el-table-column
          label="所属区域"
          align="center"
          prop="regionMergerName"
          width="180"
        />

        <el-table-column label="创建时间" align="center" prop="createTime" />

        <!--        <el-table-column-->
        <!--          label="排序"-->
        <!--          align="center"-->
        <!--          width="60"-->
        <!--          prop="orderNum"-->
        <!--        />-->

        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template #default="scope">
            <span v-hasPermi="['school:cover:edit']">
              <el-tooltip content="编辑封面" placement="top" :enterable="false">
                <el-button
                  link
                  type="primary"
                  icon="Edit"
                  @click="handleEditCover(scope.row)"
                />
              </el-tooltip>
            </span>
            <span v-hasPermi="['course:carousel:list']">
              <el-tooltip
                content="轮播图管理"
                placement="top"
                :enterable="false"
              >
                <el-button
                  link
                  type="primary"
                  icon="Management"
                  @click="handleEditSwiper(scope.row)"
                />
              </el-tooltip>
            </span>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getOrganizationList"
      />
    </el-card>

    <el-dialog
      v-model="dialogStatus.isShow"
      ref="dialogRef"
      title="编辑学校封面"
      center
      @close="handleCloseDialog"
      width="900"
    >
      <el-row>
        <div class="section-title">
          学校封面设置
          <el-tooltip effect="light" :content="tips" raw-content>
            <el-icon class="ml-1" color="#5e636e">
              <QuestionFilled />
            </el-icon>
          </el-tooltip>
        </div>
      </el-row>

      <el-form-item label="家校共育封面">
        <upload-school-cover-image
          v-if="dialogStatus.isShow"
          :cover-type="0"
          :organization-id="currentDialogData.organizationId"
          :is-linked="currentDialogData.isLinkedCoverEducation"
          :linked-cover-url="currentDialogData.coverEducation"
          :crop-width="694"
          :crop-height="430"
          v-model="currentDialogData.isSelectedEducation"
          :is-operable="true"
        ></upload-school-cover-image>
      </el-form-item>

      <el-form-item label="家校动态封面">
        <upload-school-cover-image
          v-if="dialogStatus.isShow"
          :cover-type="1"
          :organization-id="currentDialogData.organizationId"
          :is-linked="currentDialogData.isLinkedCoverNews"
          :linked-cover-url="currentDialogData.coverNews"
          :crop-width="694"
          :crop-height="430"
          v-model="currentDialogData.isSelectedNews"
          :is-operable="true"
        ></upload-school-cover-image>
      </el-form-item>

      <el-form-item label="家长课程封面">
        <upload-school-cover-image
          v-if="dialogStatus.isShow"
          :cover-type="2"
          :organization-id="currentDialogData.organizationId"
          :is-linked="currentDialogData.isLinkedCoverCourse"
          :linked-cover-url="currentDialogData.coverCourse"
          :crop-width="694"
          :crop-height="430"
          v-model="currentDialogData.isSelectedCourse"
          :is-operable="true"
        ></upload-school-cover-image>
      </el-form-item>
    </el-dialog>

    <el-dialog
      v-model="dialogStatus.swiperTable"
      title="编辑学校轮播图"
      width="80%"
      center
      append-to-body
      :show-close="true"
      @close="handelCloseSwiperDialog"
    >
      <!-- <template #header> -->
      <el-row :gutter="10" class="mb-1">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="Edit"
            @click="handleAddSwiper()"
            v-hasPermi="['course:carousel:add']"
          >
            添加轮播图
          </el-button>
        </el-col>
        <!-- <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete()"
            v-hasPermi="['system:user:remove']"
          >
            删除
          </el-button>
        </el-col> -->
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="Edit"
            @click="handleAddInnerSwiper()"
            v-hasPermi="['course:carousel:add']"
          >
            新增轮播图
          </el-button>
        </el-col>
        <right-toolbar
          :search="false"
          @queryTable="getNewsList"
        ></right-toolbar>
      </el-row>
      <!-- </template> -->
      <el-table
        :data="swiperList"
        @selection-change="handleSwiperTableChange"
        v-loading="loading"
      >
        <!-- <el-table-column type="selection" width="30" align="center" /> -->
        <el-table-column label="分类标题" align="center" prop="articleType">
          <template #default="{ row }: { row: SchoolSiteArticleVo }">
            <el-tag>
              {{ articleTypeMap.get(row.articleType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="文章标题" align="center" prop="title" />
        <el-table-column label="文章副标题" align="center" prop="subTitle" />
        <el-table-column label="创建者" align="center" prop="createBy" />
        <el-table-column label="封面" prop="status" align="center">
          <template #default="{ row }: { row: SchoolSiteArticleVo }">
            <el-image
              style="width: 100px; height: 100px"
              :src="row.cover"
              :zoom-rate="1.2"
              :max-scale="7"
              :min-scale="0.2"
              :initial-index="4"
              fit="scale-down"
            />
          </template>
        </el-table-column>

        <el-table-column label="链接" align="center" prop="content">
          <template #default="{ row }: { row: SchoolSiteArticleVo }">
            <!--  -->
            <!-- <span v-if="row.contentType === '1'"> {{ row.content }} </span> -->
            <span v-if="row.contentType === '1'"> {{ row.content }}</span>
            <span v-else> 暂无链接 </span>
          </template>
        </el-table-column>

        <el-table-column label="状态" prop="status" align="center">
          <template #default="{ row }: { row: SchoolSiteArticleVo }">
            <el-tag
              :type="CommonStatusStyleTypeMap.get(row.status ?? '') ?? 'info'"
            >
              {{ row.statusMsg }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template #default="scope">
            <el-tooltip content="详情" placement="top" :enterable="false">
              <el-button
                v-hasPermi="['course:carousel:query']"
                link
                type="primary"
                icon="FolderOpened"
                @click="handleDetail(scope.row)"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="编辑" placement="top" :enterable="false">
              <el-button
                link
                type="primary"
                icon="Edit"
                @click="handleEditNews(scope.row)"
                v-hasPermi="['course:carousel:edit']"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="移出" placement="top" :enterable="false">
              <el-button
                link
                type="primary"
                icon="Delete"
                @click="handleRemove(scope.row)"
                v-hasPermi="['course:carousel:remove']"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <pagination
        v-show="swiperTotal > 0"
        :total="swiperTotal"
        v-model:page="newsParams.pageNum"
        v-model:limit="newsParams.pageSize"
        @pagination="getNewsList"
      />
    </el-dialog>
    <!-- 非轮播图列表 -->
    <el-dialog
      v-model="dialogStatus.innerSwiperTable"
      title="非轮播图新闻列表"
      width="75%"
      center
      append-to-body
      :show-close="true"
      @close="handelCloseInnerSwiperTable"
    >
      <!-- <template #header> -->
      <el-row :gutter="10" class="mb-1">
        <!-- <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="Edit"
              @click="handleAddInnerSwiper()"
              v-hasPermi="['system:user:edit']"
            >
              新增轮播图
            </el-button>
          </el-col> -->
        <!-- <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="Delete"
              :disabled="multiple"
              @click="handleDelete()"
              v-hasPermi="['system:user:remove']"
            >
              删除
            </el-button>
          </el-col> -->
        <right-toolbar
          :search="false"
          @queryTable="getNoSetNewsList"
        ></right-toolbar>
      </el-row>
      <!-- </template> -->
      <el-table
        :data="innerSwiperList"
        @selection-change="handleNoSetSelectionChange"
        v-loading="loading"
      >
        <!-- <el-table-column type="selection" width="30" align="center" /> -->
        <el-table-column label="分类标题" align="center" prop="articleType">
          <template #default="{ row }: { row: SchoolSiteArticleVo }">
            <el-tag>
              {{ articleTypeMap.get(row.articleType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="文章标题" align="center" prop="title" />
        <el-table-column label="文章副标题" align="center" prop="subTitle" />
        <el-table-column label="创建者" align="center" prop="createBy" />
        <el-table-column label="封面" prop="status" align="center">
          <template #default="{ row }: { row: SchoolSiteArticleVo }">
            <el-image
              style="width: 100px; height: 100px"
              :src="row.cover"
              :zoom-rate="1.2"
              :max-scale="7"
              :min-scale="0.2"
              :initial-index="4"
              fit="scale-down"
            />
          </template>
        </el-table-column>

        <el-table-column label="链接" align="center" prop="content">
          <template #default="{ row }: { row: SchoolSiteArticleVo }">
            <!--  -->
            <span v-if="row.contentType === '1'"> {{ row.content }}</span>
            <span v-else> 暂无链接 </span>
          </template>
        </el-table-column>

        <el-table-column label="状态" prop="status" align="center">
          <template #default="{ row }: { row: SchoolSiteArticleVo }">
            <el-tag
              :type="CommonStatusStyleTypeMap.get(row.status ?? '') ?? 'info'"
            >
              {{ row.statusMsg }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template #default="scope">
            <!-- <el-tooltip content="详情" placement="top" :enterable="false"> -->
            <el-button
              link
              type="primary"
              v-hasPermi="['course:carousel:edit']"
              @click="handleSetSwiper(scope.row)"
              >设为轮播图</el-button
            >
            <!-- </el-tooltip> -->
            <!-- <el-tooltip content="编辑" placement="top" :enterable="false">
              <el-button
                link
                type="primary"
                icon="Edit"
                @click="handleEditNews(scope.row)"
                v-hasPermi="['system:user:edit']"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top" :enterable="false">
              <el-button
                link
                type="primary"
                icon="Delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['system:user:remove']"
              ></el-button>
            </el-tooltip> -->
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <pagination
        v-show="innerSwiperTotal > 0"
        :total="innerSwiperTotal"
        v-model:page="noSetNewsParams.pageNum"
        v-model:limit="noSetNewsParams.pageSize"
        @pagination="getNoSetNewsList"
      />
    </el-dialog>

    <el-dialog
      v-model="dialogStatus.visible"
      :title="dialogStatus.title"
      width="70%"
      center
      append-to-body
      :show-close="true"
      @close="handleCloseNewsDialog"
      :before-close="handleBeforeCloseNewsDialog"
    >
      <el-form
        :model="setNewsBO"
        ref="addFormRef"
        :inline="true"
        label-width="100px"
        class="dialogForm"
        :rules="formRules"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="新闻标题" prop="title">
              <el-input
                v-model="setNewsBO.title"
                :disabled="dialogStatus.isDisabled"
                placeholder="请输入"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="新闻副标题" prop="title">
              <el-input
                v-model="setNewsBO.subTitle"
                :disabled="dialogStatus.isDisabled"
                placeholder="请输入"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="6">
            <el-form-item label="详细类别" prop="articleType">
              <el-select
                v-model="setNewsBO.articleType"
                :disabled="dialogStatus.isDisabled"
                clearable
                placeholder="详细类别"
              >
                <el-option
                  v-for="item in selectArr.newsTypeArr"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item
              label="是否轮播"
              prop="isTop"
              :disabled="dialogStatus.isDisabled"
            >
              <el-select
                v-model="setNewsBO.isTop"
                :disabled="dialogStatus.isDisabled"
                clearable
                placeholder="是否轮播"
              >
                <el-option
                  v-for="item in selectArr.isTopArr"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-form-item label="新闻封面" prop="cover">
            <upload-school-article-cover
              v-if="dialogStatus.visible"
              @getCoverUrl="getCoverUrl"
              :cover-type="1"
              :organization-id="dialogStatus.organizationId"
              :is-linked="dialogStatus.isLinked"
              :linked-cover-url="dialogStatus.cover"
              :crop-width="200"
              :crop-height="200"
              v-model="dialogStatus.isSelected"
              :is-operable="dialogStatus.mode === DialogModeEnum.EDIT"
            ></upload-school-article-cover>
          </el-form-item>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="文章摘要" prop="introduction">
              <div class="flex" style="flex: 1">
                <el-input
                  v-model="setNewsBO.introduction"
                  :disabled="dialogStatus.isDisabled"
                  maxlength="256"
                  placeholder="请输入摘要"
                  rows="4"
                  type="textarea"
                />
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="文章类型" prop="contentType">
              <el-radio-group
                :disabled="dialogStatus.isDisabled"
                v-model="setNewsBO.contentType"
                size="ml-4"
              >
                <el-radio label="1" size="large">外部链接</el-radio>
                <el-radio label="2" size="large">富文本</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row v-if="setNewsBO.contentType === '2'">
          <el-col :span="24">
            <el-form-item label="页面内容" prop="content">
              <div style="border: 1px solid #ccc" v-loading="editorLoading">
                <Toolbar
                  style="border-bottom: 1px solid #ccc"
                  :editor="editorRef"
                  :disabled="dialogStatus.isDisabled"
                  :defaultConfig="toolbarConfig"
                  mode="default"
                />
                <editor
                  style="height: 400px; overflow-y: hidden"
                  v-model="currentRichContent"
                  :defaultConfig="editorConfig"
                  mode="default"
                  @onCreated="handleCreated"
                />
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row v-if="setNewsBO.contentType === '1'">
          <el-col :span="24">
            <el-form-item label="链接">
              <el-input
                v-model="currentLinkContent"
                :disabled="dialogStatus.isDisabled"
                placeholder="请输入外部链接"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <el-button type="primary" icon="Check" @click="handleAddSubmit">
          提交
        </el-button>
        <el-button icon="Close" @click="dialogStatus.visible = false"
          >关闭</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {
  getRootOrganizationList as getRootOrganizationListApi,
  getRootOrganizationTypeList as getRootOrganizationTypeListApi,
  getOrganizationCoverList as getOrganizationCoverListApi,
  getOrganizationSwiperList as getSwiperListApi,
  getSchoolNewsList as getSchoolNewsListApi,
  setSwiper as setSwiperApi,
  addSchoolNews as addSchoolNewsApi,
  getSchoolNewsDetail as getSchoolNewsDetailApi,
  deleteSchoolNews as deleteSchoolNewsApi,
} from "@/service/api/school/image";
import { ElForm, ElTable } from "element-plus";
import to from "await-to-js";
import { BasePageResponse, BaseResponse } from "@/service/api/type.ts";
import Pagination from "@/components/Pagination/index.vue";
import {
  SchoolSiteHomePageVo,
  SysDictDataVo,
  SysOrganizationVo,
} from "@/service/api/school/image/types.ts";
import { SchoolSiteArticleVo } from "@/service/api/school/news/types.ts";
import { DialogModeEnum } from "@/enums/dialogEnum.ts";
import { QuestionFilled } from "@element-plus/icons-vue";
import UploadSchoolCoverImage from "@/components/Upload/uploadSchoolCoverImage.vue";
import { SchoolCoverTypeEnum } from "@/enums/schoolCoverTypeEnum.ts";
import {
  CommonStatusMap,
  CommonStatusStyleTypeMap,
  articleTypeMap,
} from "@/maps/commonMaps.ts";
import { IToolbarConfig } from "@wangeditor/editor";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import "@wangeditor/editor/dist/css/style.css"; // 引入 css

// 富文本编辑器工具栏配置
const toolbarConfig: IToolbarConfig = {
  excludeKeys: ["group-video", "fullScreen"],
};
const editorLoading = ref<boolean>(false);

// 配置editor
const editorConfig = {
  placeholder: "请输入新闻内容...",
  MENU_CONF: {
    uploadImage: {
      customUpload: {},
    },
  },
};
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();

const handleCreated = (editor: any) => {
  editorRef.value = editor;
  console.log("created", editor);
};

const queryFormRef = ref(ElForm);

const treeTableRef = ref(ElTable);
const showSearch = ref(true);
const loading = ref(false);

const tips = `
封面图片最小尺寸：694x430
`;

const queryParams = reactive({
  name: "",
  type: "",
  parentId: 0,
  orderByColumn: "createTime",
  orderType: "desc",
  pageSize: 10,
  pageNum: 1,
});

// 获取轮播图列表
const initNewsParams = {
  id: "",
  status: "",
  pageSize: 10,
  pageNum: 1,
  title: "",
  sendTime: "",
  content: "",
  cover: "",
  introduction: "",
  // 只拿置顶了的新闻
  isTop: true,
  siteType: "",
  articleType: "",
  url: "",
  isRich: false,
  timeRange: [null, null],
  orderByColumn: "createTime",
  orderType: "desc",
  organizationId: "",
};
// 获取非轮播图新闻列表
const initNoSetNewsParams = {
  id: "",
  status: "",
  pageSize: 10,
  pageNum: 1,
  title: "",
  sendTime: "",
  content: "",
  cover: "",
  introduction: "",
  // 只拿置顶了的新闻
  isTop: false,
  siteType: "",
  articleType: "",
  url: "",
  isRich: false,
  timeRange: [null, null],
  orderByColumn: "createTime",
  orderType: "desc",
  organizationId: "",
};

// 初始dialog数据
const initDialogData = {
  organizationId: "",
  // 封面的url
  coverEducation: "",
  coverNews: "",
  coverCourse: "",
  // 是否关联了学校封面
  isLinkedCoverEducation: false,
  isLinkedCoverNews: false,
  isLinkedCoverCourse: false,
  // 是否选择了封面
  isSelectedEducation: false,
  isSelectedNews: false,
  isSelectedCourse: false,
  covers: <SchoolSiteHomePageVo[]>[],
};

// 初始dialog状态
const initDialogStatus = {
  isShow: false,
  mode: DialogModeEnum.NEW,
  title: "",
  swiperTableTitle: "",
  swiperTable: false,
  innerSwiperTable: false,
  innerSwiperTableTitle: "",
  isDisabled: false,
  preview: false,
  visible: false,
  articleTable: false,
  isLinked: false,
  articleTableTitle: "",
  cover: "",
  isSelected: false,
  organizationId: "",
};

const initSetNewsBO = {
  id: "",
  status: "0",
  title: "",
  content: "",
  cover: "",
  introduction: "",
  isTop: true,
  articleType: "",
  contentType: "1",
  organizationId: "",
};

const dialogData = reactive({
  // 临时数据
  currentDialogData: {
    ...initDialogData,
  },
  // 控制dialog状态
  dialogStatus: { ...initDialogStatus },
  rules: {
    name: [{ required: true, message: "机构名不能为空", trigger: "blur" }],
    regionId: [
      { required: true, message: "机构地区不能为空", trigger: "change" },
    ],
    status: [{ required: true, message: "状态不能为空", trigger: "change" }],
    type: [{ required: true, message: "状态不能为空", trigger: "change" }],
  },
  newsParams: { ...initNewsParams },
  noSetNewsParams: { ...initNoSetNewsParams },
  setNewsBO: { ...initSetNewsBO },
});

/**
 * 表单校验规则
 */
const formRules = {
  title: [{ required: true, message: "标题不能为空", trigger: "blur" }],
  articleType: [
    { required: true, message: "新闻类型不能为空", trigger: "blur" },
  ],
  isTop: [{ required: true, message: "是否置顶不能为空", trigger: "blur" }],
  introduction: [{ required: true, message: "摘要不能为空", trigger: "blur" }],
  // content: [{ required: true, message: "新闻内容不能为空", trigger: "blur" }],
};

const {
  currentDialogData,
  dialogStatus,
  newsParams,
  noSetNewsParams,
  setNewsBO,
} = toRefs(dialogData);

const dialogRef = ref();

const rootOrganizationTypeMap = ref<Map<string, string>>(new Map());
const schoolOrganizationType = ref();
// 选择框数据
const selectArr = reactive({
  rootOrganizationTypeList: <SysDictDataVo[]>[],
  subOrganizationTypeList: <SysDictDataVo[]>[],
  // 类型
  typeArr: [
    {
      value: "0",
      label: "其他类型",
    },
    {
      value: "1",
      label: "学校类型",
    },
    {
      value: "2",
      label: "班级类型",
    },
    {
      value: "3",
      label: "教育机构类型",
    },
    {
      value: "4",
      label: "专家组织类型",
    },
    {
      value: "5",
      label: "工作室类型",
    },
    {
      value: "6",
      label: "年级类型",
    },
    {
      value: "7",
      label: "公司类型",
    },
  ],
  // 状态
  statusArr: [
    {
      value: "0",
      label: "正常",
    },
    {
      value: "1",
      label: "停用",
    },
  ],
  newsTypeArr: [
    {
      value: "0",
      label: "理念介绍",
    },
    {
      value: "1",
      label: "政策解读",
    },
    {
      value: "2",
      label: "热点新闻",
    },
    {
      value: "3",
      label: "共育活动",
    },
  ],
  isTopArr: [
    {
      value: true,
      label: "是",
    },
    {
      value: false,
      label: "否",
    },
  ],
});

// 树结构数据
const organizationList = ref<SysOrganizationVo[]>([]);

const total = ref(0);

/**
 * 获取组织树
 */
const getOrganizationList = async (): Promise<boolean> => {
  queryParams.type = schoolOrganizationType.value.value;
  const [err, res] = await to<BasePageResponse<SysOrganizationVo>, any>(
    getRootOrganizationListApi(queryParams),
  );
  if (!err) {
    console.log(res);
    organizationList.value = res?.rows ?? [];
    total.value = Number(res?.total);

    organizationList.value.forEach((item) => {
      item.typeMsg = rootOrganizationTypeMap.value.get(item.type);
    });

    return true;
  }
  return false;
};

// // 获取轮播图文章
// const getOrganizationSwiperList = async () => {
//   const [err, res] = await to(getOrganizationSwiperListApi());
// };

// 提交查询按钮
const handleQuery = () => {
  getOrganizationList();
};

// 重置按钮
const resetQuery = () => {
  queryFormRef.value.resetFields();
  console.log(queryParams);
  getOrganizationList();
};

/**
 * 处理编辑封面按钮
 * @param row
 */
const handleEditCover = async (row: any) => {
  loading.value = true;
  const [err, res] = await to<BasePageResponse<SchoolSiteHomePageVo>, any>(
    getOrganizationCoverListApi({ organizationId: row.id }),
  );

  if (!err) {
    currentDialogData.value.organizationId = row.id;
    currentDialogData.value.covers = res?.rows ?? [];
    currentDialogData.value.covers.forEach((item) => {
      if (item.type === SchoolCoverTypeEnum.EDUCATION) {
        currentDialogData.value.isLinkedCoverEducation = true;
        currentDialogData.value.coverEducation = item.cover ?? "";
      } else if (item.type === SchoolCoverTypeEnum.NEWS) {
        currentDialogData.value.isLinkedCoverNews = true;
        currentDialogData.value.coverNews = item.cover ?? "";
      } else if (item.type === SchoolCoverTypeEnum.COURSE) {
        currentDialogData.value.isLinkedCoverCourse = true;
        currentDialogData.value.coverCourse = item.cover ?? "";
      }
    });
    dialogStatus.value.isShow = true;
    loading.value = false;
  }

  // 非根节点
  // if (row.parentId !== "0") {
  //   // const currentTree = findTree(organizationTree.organizationTree, row);
  //   // console.log(currentTree);
  //   // // 拼接所有父节点名称
  //   // const nameArr = await getParentNames(row);
  //   // fullName.value = nameArr.reverse().join(" / ");
  //
  //   const response = await getSubOrganizationTypeList(row.parent.type);
  //
  //   if (response) {
  //     let index = row.fullName.lastIndexOf("/");
  //     fullName.value = row.fullName.substring(0, index);
  //     dialogStatus.value.title = "编辑组织";
  //     dialogStatus.value.isNode = true;
  //     dialogStatus.value.isRoot = false;
  //   }
  // } else {
  //   dialogStatus.value.title = "编辑根组织";
  //   dialogStatus.value.isRoot = true;
  //   dialogStatus.value.isNode = false;
  // }
  //
  // const [err, res] = await to<BaseResponse<SysOrganizationVo>, any>(
  //     getOrganizationDetailApi(row.id),
  // );
  // if (!err) {
  //   currentDialogData.value = res?.data ?? initDialogData;
  //   currentRegionId.value = res?.data?.regionId ?? "";
  // }
  // dialogStatus.value.mode = DialogModeEnum.EDIT;
  // dialogStatus.value.isShow = true;
  // nextTick(() => {
  //   addRootFormRef.value?.clearValidate();
  // });
};

/**
 * 处理编辑封面按钮
 * @param row
 */
const handleEditSwiper = async (row: any) => {
  loading.value = true;

  newsParams.value.organizationId = row.id;
  // dialogData.value.organizationId = row.id;
  dialogStatus.value.organizationId = row.id;
  setNewsBO.value.organizationId = row.id;
  noSetNewsParams.value.organizationId = row.id;
  // console.log(row, dialogData.value);
  dialogStatus.value.swiperTableTitle = "轮播图列表";
  const [err] = await to(getNewsList());
  if (!err) {
    // dialogStatus.value.covers = res?.rows ?? [];
    dialogStatus.value.swiperTable = true;
    loading.value = false;
  } else {
    loading.value = false;
  }
};

const swiperList = ref<SchoolSiteArticleVo[]>([]);
const innerSwiperList = ref<SchoolSiteArticleVo[]>([]);
const swiperTotal = ref(0);
const innerSwiperTotal = ref(0);
/**
 * 获取轮播图列表
 */
const getNewsList = async (): Promise<boolean> => {
  let [err, res] = await to<BasePageResponse<SchoolSiteArticleVo>, any>(
    getSchoolNewsListApi(newsParams.value),
  );
  if (!err) {
    swiperList.value = res?.rows ?? [];
    swiperTotal.value = Number(res?.total ?? 0);
    swiperList.value.forEach((item) => {
      item.statusMsg = CommonStatusMap.get(item.status ?? "") ?? "未知";
    });
    return true;
  }
  return false;
};

// 添加轮播图按钮
const handleAddSwiper = async () => {
  await getNoSetNewsList();
  dialogStatus.value.innerSwiperTable = true;
  dialogStatus.value.innerSwiperTableTitle = "非轮播图新闻列表";
};

// 获取非轮播图列表
const getNoSetNewsList = async () => {
  const [err, res] = await to(getSchoolNewsListApi(noSetNewsParams.value));
  if (!err) {
    innerSwiperList.value = res?.rows ?? [];
    innerSwiperTotal.value = Number(res?.total ?? 0);
    innerSwiperList.value.forEach((item) => {
      item.statusMsg = CommonStatusMap.get(item.status ?? "") ?? "未知";
    });
  } else {
    ElMessage({
      type: "error",
      message: "获取失败",
    });
  }
};

// 设为轮播图
const handleSetSwiper = async (row: any) => {
  console.log(row);
  row.isTop = true;
  const [err] = await to(setSwiperApi(row));
  if (!err) {
    await getNoSetNewsList();
    ElMessage({
      type: "success",
      message: "操作成功",
    });
  }
};

// 新增新闻按钮
const handleAddInnerSwiper = () => {
  dialogStatus.value.mode = DialogModeEnum.EDIT;

  dialogStatus.value.title = "新增学校新闻";
  dialogStatus.value.visible = true;
};

const currentLinkContent = ref();
const currentRichContent = ref();

/**
 * 获取学校新闻详情
 * @param id
 */
const getSchoolNewsDetail = async (id: string): Promise<boolean> => {
  let [err, res] = await to<BaseResponse<SchoolSiteArticleVo>, any>(
    getSchoolNewsDetailApi(id),
  );
  if (!err) {
    console.log(res);
    setNewsBO.value = res?.data ?? initSetNewsBO;
    if (setNewsBO.value.cover && setNewsBO.value.cover != "") {
      dialogStatus.value.cover = setNewsBO.value.cover;
      dialogStatus.value.isLinked = true;
    }
    if (setNewsBO.value.contentType === "1") {
      // 链接
      currentLinkContent.value = setNewsBO.value.content;
    } else {
      // 富文本
      currentRichContent.value = setNewsBO.value.content;
    }
    console.log(dialogStatus.value.cover);
    return true;
  }
  return false;
};

/**
 * 处理详情按钮
 * @param row
 */
const handleDetail = async (row: any) => {
  loading.value = true;
  dialogStatus.value.mode = DialogModeEnum.DETAIL;
  const response = await getSchoolNewsDetail(row.id);

  if (response) {
    dialogStatus.value.title = "学校新闻详情";
    console.log(editorRef.value);
    // 这是个异步方法！！！！！！必须用await
    editorRef.value && (await editorRef.value.disable());
    dialogStatus.value.isDisabled = true;
    dialogStatus.value.visible = true;
    addFormRef.value?.clearValidate();
    loading.value = false;
  }
};
const ids = ref([]);
/**
 * 编辑按钮
 * @param row
 */
const handleEditNews = async (row?: any) => {
  console.log(dialogStatus.value.cover);
  dialogStatus.value.mode = DialogModeEnum.EDIT;
  loading.value = true;
  const id = row?.id ?? ids.value[0];
  const response = await getSchoolNewsDetail(id);
  if (response) {
    dialogStatus.value.isDisabled = false;
    editorRef.value && editorRef.value.enable();
    dialogStatus.value.title = "编辑学校新闻";
    dialogStatus.value.isDisabled = false;
    dialogStatus.value.visible = true;
    loading.value = false;
  }
};

const single = ref(true);
const multiple = ref(true);
const noSetMultiple = ref(true);
// 轮播图列表勾选
const handleSwiperTableChange = (selection: any) => {
  ids.value = selection.map((item: any) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
  console.log(ids.value);
};

// 非轮播图列表勾选
const handleNoSetSelectionChange = (selection: any) => {
  ids.value = selection.map((item: any) => item.id);
  single.value = selection.length != 1;
  noSetMultiple.value = !selection.length;
  console.log(ids.value);
};

// 移出轮播图列表按钮
const handleRemove = async (row: any) => {
  const [err, confirm] = await to<string, string>(
    ElMessageBox.confirm("是否确认移出新闻，移出后可在文章列表中找到", "警告", {
      type: "warning",
      confirmButtonText: "确认",
      cancelButtonText: "取消",
    }),
  );

  if (err === "cancel") {
    ElMessage({
      type: "info",
      message: "取消移出",
    });
  } else if (confirm === "confirm") {
    row.isTop = false;
    const [err] = await to<BaseResponse<any>, any>(setSwiperApi(row));
    if (!err) {
      ElMessage({
        type: "success",
        message: "移出成功",
      });
      getNewsList();
    } else {
      ElMessage({
        type: "error",
        message: "移出失败",
      });
      getNewsList();
    }
  }
};

/**
 * 处理批量移出按钮
 * @param row
 */
// const handleDelete = async (row?: any) => {
//   // 询问确认删除
//   const [err, confirm] = await to<string, string>(
//     ElMessageBox.confirm("是否确认移出新闻，移出后可在文章列表中找到", "警告", {
//       type: "warning",
//       confirmButtonText: "确认",
//       cancelButtonText: "取消",
//     }),
//   );

//   if (err === "cancel") {
//     ElMessage({
//       type: "info",
//       message: "取消删除",
//     });
//   } else if (confirm === "confirm") {
//     const _ids = row?.id ?? ids.value;
//     console.log(_ids);
//     row.isTop = false;
//     if (row) {
//       const [err] = await to<BaseResponse<any>, any>(setSwiperApi(row));
//       if (!err) {
//         ElMessage({
//           type: "success",
//           message: "移出成功",
//         });
//         getNewsList();
//       } else {
//         ElMessage({
//           type: "error",
//           message: "移出失败",
//         });
//         getNewsList();
//       }
//     }
//     // } else {
//     //   for (let item in _ids) {
//     //     const [err] = await to<BaseResponse<any>, any>(setSwiperApi(_ids[item]));
//     //     // await to<BaseResponse<any>, any>(deleteSchoolNewsApi(_ids));
//     //     if (!err) {
//     //       ElMessage({
//     //         type: "success",
//     //         message: "移出成功",
//     //       });
//     //     }
//     //   }
//     //   getNewsList();
//     // }
//   }
// };

// 获取上传后的url
const getCoverUrl = (url: string) => {
  setNewsBO.value.cover = url;
};

const addFormRef = ref();
/**
 * 处理对话框的提交按钮
 */
// const handleAddSubmit = () => {
//   // addFormRef.value?.validate(async (valid: boolean) => {
//   //   // 验证通过
//   //   if (valid) {
//   //     loading.value = true;
//   //     // 修改
//   //     if (dialogStatus.value.mode === DialogModeEnum.EDIT) {
//   //       // 如果修改了地区
//   //       if (currentRegionId.value != currentDialogData.value.regionId) {
//   //         // 如果改变了根节点的地区
//   //         // 找到根节点对应树
//   //         // 保存新的regionId
//   //         const newRegionId = currentDialogData.value.regionId;
//   //         const currentTree = organizationTree.organizationTree.find(
//   //             (item: any) => item.id === currentDialogData.value.id,
//   //         );
//   //         console.log(currentTree);
//   //         // 遍历改变所有子节点的地区
//   //         await updateNodeRegion(currentTree, newRegionId);
//   //       }
//   //       // 未修改地区
//   //       else {
//   //         const [err] = await to(organizationEditApi(currentDialogData.value));
//   //         if (!err) {
//   //           dialogStatus.value = Object.assign({}, initDialogStatus);
//   //           currentDialogData.value = Object.assign({}, initDialogData);
//   //           // 等待删除完成？
//   //           // setTimeout(async () => {
//   //           //   await getOrganizationTree();
//   //           // }, 1000);
//   //           ElMessage({
//   //             type: "success",
//   //             message: "修改成功",
//   //           });
//   //         }
//   //       }
//   //     }
//   //     // 无id为新增
//   //     else {
//   //       const [err] = dialogStatus.value.isRoot
//   //           ? await to(createRootOrganizationApi(currentDialogData.value))
//   //           : await to(createOrganizationApi(currentDialogData.value));
//   //       if (!err) {
//   //         dialogStatus.value = Object.assign({}, initDialogStatus);
//   //         currentDialogData.value = Object.assign({}, initDialogData);
//   //         // setTimeout(async () => {
//   //         //   await getOrganizationTree();
//   //         // }, 1000);
//   //         ElMessage({
//   //           type: "success",
//   //           message: "新增成功",
//   //         });
//   //       }
//   //     }
//   //     loading.value = false;
//   //   }
//   // });
// };

const handleAddSubmit = () => {
  console.log(1);

  addFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      if (dialogStatus.value.isSelected) {
        const [err, confirm] = await to<string, string>(
          ElMessageBox.confirm("你有图片未上传，是否确定提交?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }),
        );
        if (err === "cancel") {
          ElMessage({
            type: "info",
            message: "已取消关闭",
          });
        } else if (confirm === "confirm") {
          ElMessage({
            type: "info",
            message: "已确定提交",
          });
          if (setNewsBO.value.contentType === "1") {
            setNewsBO.value.content = currentLinkContent.value;
          } else {
            setNewsBO.value.content = currentRichContent.value;
          }
          if (setNewsBO.value.id) {
            const [err] = await to<BaseResponse<any>, any>(
              setSwiperApi(setNewsBO.value),
            );
            if (!err) {
              ElMessage({
                type: "success",
                message: "修改成功",
              });
              dialogStatus.value.visible = false;
              getNewsList();
            } else {
              ElMessage({
                type: "error",
                message: "修改失败",
              });
            }
          } else {
            console.log(setNewsBO.value);
            const [err] = await to(addSchoolNewsApi(setNewsBO.value));
            if (!err) {
              ElMessage({
                type: "success",
                message: "新增成功",
              });
              dialogStatus.value.visible = false;
              getNewsList();
            } else {
              ElMessage({
                type: "error",
                message: "新增失败",
              });
              dialogStatus.value.visible = false;
              getNewsList();
            }
          }
        }
      } else {
        if (setNewsBO.value.contentType === "1") {
          setNewsBO.value.content = currentLinkContent.value;
        } else {
          setNewsBO.value.content = currentRichContent.value;
        }
        if (setNewsBO.value.id) {
          const [err] = await to<BaseResponse<any>, any>(
            setSwiperApi(setNewsBO.value),
          );
          if (!err) {
            ElMessage({
              type: "success",
              message: "修改成功",
            });
            dialogStatus.value.visible = false;
            getNewsList();
          } else {
            ElMessage({
              type: "error",
              message: "修改失败",
            });
          }
        } else {
          console.log(setNewsBO.value);
          const [err] = await to(addSchoolNewsApi(setNewsBO.value));
          if (!err) {
            ElMessage({
              type: "success",
              message: "新增成功",
            });
            dialogStatus.value.visible = false;
            getNewsList();
          } else {
            ElMessage({
              type: "error",
              message: "新增失败",
            });
            dialogStatus.value.visible = false;
            getNewsList();
          }
        }
      }
    }
  });
};
/**
 * 处理对话框关闭
 */
const handleCloseDialog = () => {
  // 初始化
  dialogStatus.value = Object.assign({}, initDialogStatus);
  currentDialogData.value = Object.assign({}, initDialogData);
  backToDialogTop();
  // currentRegionId.value = "";
  // addRootFormRef.value?.clearValidate();
  // regionCascaderRef.value?.cascaderPanelRef?.clearCheckedNodes();
  getOrganizationList();
};

/**
 * 处理回到窗口顶部
 * @param instant
 */
const backToDialogTop = (instant = true) => {
  if (dialogRef.value.dialogContentRef) {
    const dialogBodyEl =
      dialogRef.value.dialogContentRef.$el.querySelector(".el-dialog__body");
    const behavior = instant ? "instant" : "smooth";
    dialogBodyEl.scrollTo({ top: 0, behavior });
  }
};

const handleBeforeCloseNewsDialog = async (done: DoneFn) => {
  if (dialogStatus.value.isSelected) {
    // 询问是否关闭
    const [err, confirm] = await to<string, string>(
      ElMessageBox.confirm("你有图片未上传，是否确定关闭对话框?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }),
    );
    if (err === "cancel") {
      ElMessage({
        type: "info",
        message: "已取消关闭",
      });
    } else if (confirm === "confirm") {
      ElMessage({
        type: "info",
        message: "强制关闭对话框",
      });
      done();
    }
  } else {
    done();
  }
};

// 关闭新增文章dialog
const handleCloseNewsDialog = async () => {
  // dialogStatus.value.visible = false
  // 刷新轮播图列表
  const currentOrganizationId = setNewsBO.value.organizationId;
  dialogStatus.value.isDisabled = false;

  dialogStatus.value.cover = "";
  dialogStatus.value.isLinked = false;

  dialogStatus.value.visible = false;
  setNewsBO.value = Object.assign({}, initSetNewsBO);
  setNewsBO.value.organizationId = currentOrganizationId;
  dialogStatus.value.organizationId = currentOrganizationId;
  currentLinkContent.value = "";
  currentRichContent.value = "";
  await getNewsList();
};

/**
 * 获取根组织类型
 */
const getRootOrganizationTypeList = async (): Promise<boolean> => {
  const [err, res] = await to<BasePageResponse<SysDictDataVo>, any>(
    getRootOrganizationTypeListApi(),
  );
  if (!err) {
    selectArr.rootOrganizationTypeList = res?.rows ?? [];
    selectArr.rootOrganizationTypeList.forEach((item) => {
      rootOrganizationTypeMap.value.set(item.value ?? "", item.label);
      if (item.label === "学校") {
        schoolOrganizationType.value = item;
      }
      console.log(schoolOrganizationType.value);
    });

    return true;
  }

  return false;
};

// 关闭dialog时触发
// const closeDialog = () => {};

onMounted(async () => {
  await getRootOrganizationTypeList();
  getOrganizationList();
  // getBackOrganizationTree();
});
</script>

<style scoped lang="scss">
.section-title {
  display: flex;
  align-items: center;
  font-size: 16px;
  font-weight: bold;
  color: #333333;
  padding-bottom: 10px;
}
</style>
